package com.ruoyi.xuexiao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.config.MinIOConfigProperties;
import com.ruoyi.xuexiao.domain.entity.KsFile;
import com.ruoyi.xuexiao.mapper.KsFileMapper;
import com.ruoyi.xuexiao.service.FileDiskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 获取文件夹树
 *
 * @author ：郭伟明
 * @date ：Created in 2024/5/29 16:051
 * @description：
 */
@Service
public class FileDiskServiceImpl extends ServiceImpl<KsFileMapper, KsFile> implements FileDiskService {

    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    /**
     * 获取文件夹树下一次
     * @param folderName
     * @param filter
     * @return
     */
    @Override
    public Map<String, Object> getFileStructure(@RequestParam(required = false) String folderName, @RequestParam(required = false) String filter) {
        // 根文件夹路径
        File folder;
        if (folderName==null){
            folder = new File(minIOConfigProperties.getUploaddir());
        }else {
            folder = new File(folderName);

        }
        // 使用 LinkedHashMap 以保持插入顺序
        Map<String, Object> response = new LinkedHashMap<>();

        if (folder.exists() && folder.isDirectory()) {
            Map<String, Object> data = new LinkedHashMap<>();
            data.put("name", folder.getName());
            // 添加完整路径，并替换路径分隔符为单斜杠
            data.put("fullPath", folder.getAbsolutePath().replace("\\", "/"));
            // 修改键名为 "children"
            data.put("children", getNextLevelFilesAndFolders(folder, filter));
            return data;
        } else {
            throw new RuntimeException("指定路径不是一个文件夹或者文件夹不存在");
        }
    }

    private List<Map<String, Object>> getNextLevelFilesAndFolders(File folder, String filter) {
        List<Map<String, Object>> filesAndFoldersList = new ArrayList<>();
        File[] filesAndFolders = folder.listFiles();

        if (filesAndFolders != null) {
            // 对文件和文件夹进行排序
            Arrays.sort(filesAndFolders, Comparator.comparing(File::getName));

            for (File fileOrFolder : filesAndFolders) {
                if (fileOrFolder.isDirectory() && (filter == null || fileOrFolder.getName().contains(filter))) {
                    // 使用 LinkedHashMap 以保持插入顺序'
                    Map<String, Object> fileOrFolderMap = new LinkedHashMap<>();
                    // 将文件夹的名称作为键值
                    fileOrFolderMap.put("name", fileOrFolder.getName());
                    // 添加完整路径，并替换路径分隔符为单斜杠
                    fileOrFolderMap.put("fullPath", fileOrFolder.getAbsolutePath().replace("\\", "/"));
                    filesAndFoldersList.add(fileOrFolderMap);
                }
            }
        }

        return filesAndFoldersList;
    }

    private List<Map<String, Object>> getNextLevelFilesAndFolders(File folder) {
        List<Map<String, Object>> filesAndFoldersList = new ArrayList<>();
        File[] filesAndFolders = folder.listFiles();

        if (filesAndFolders != null) {
            // 对文件和文件夹进行排序
            Arrays.sort(filesAndFolders, Comparator.comparing(File::getName));

            for (File fileOrFolder : filesAndFolders) {
                if (fileOrFolder.isDirectory()) {
                    // 使用 LinkedHashMap 以保持插入顺序
                    Map<String, Object> fileOrFolderMap = new LinkedHashMap<>();
                    // 将文件夹的名称作为键值
                    fileOrFolderMap.put("name", fileOrFolder.getName());
                    // 添加完整路径，并替换路径分隔符为单斜杠
                    fileOrFolderMap.put("fullPath", fileOrFolder.getAbsolutePath().replace("\\", "/"));
                    filesAndFoldersList.add(fileOrFolderMap);
                }
            }
        }
        return filesAndFoldersList;
    }

    /**
     * 获取文件夹树上一层
     * @param folderName
     * @param rootFolderPath
     * @return
     */
    @Override
    public Map<String, Object> getFileStructureParent(String folderName, String rootFolderPath) {
        // 确保文件路径的分隔符一致
        String standardizedRootFolderPath = rootFolderPath.replace("/", File.separator).replace("\\", File.separator);
        String standardizedFolderName = folderName.replace("/", File.separator).replace("\\", File.separator);

        // 截取路径，去掉目标子路径部分
        String trimmedPath = standardizedRootFolderPath.replaceFirst(Pattern.quote(standardizedFolderName) + "$", "");

        // 创建文件对象
        File folder = new File(trimmedPath);
        Map<String, Object> root = new LinkedHashMap<>();

        if (folder.exists() && folder.isDirectory()) {
            List<Map<String, Object>> filesList = new ArrayList<>();
            File[] filesAndFolders = folder.listFiles();

            if (filesAndFolders != null) {
                Arrays.sort(filesAndFolders, Comparator.comparing(File::getName));

                for (File fileOrFolder : filesAndFolders) {
                    Map<String, Object> fileMap = new LinkedHashMap<>();
                    fileMap.put("name", fileOrFolder.getName());
                    fileMap.put("fullPath", folder.getAbsolutePath().replace("\\", "/"));
                    filesList.add(fileMap);
                }
            }

            root.put("name", folder.getName());
            root.put("fullPath", folder.getAbsolutePath().replace("\\", "/"));
            root.put("children", getNextLevelFilesAndFolders(new File(rootFolderPath.substring(0, rootFolderPath.lastIndexOf("/")))));
        } else {
            root.put("error", "指定路径不是一个文件夹或者文件夹不存在");
        }
        return root;
    }

}